package thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author study
 * @version 1.0
 * @date 2020/8/16 15:43
 */
public class Thread01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(10);

        /**
         * 方法执行完后的处理
         */
       /* CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("运行结果" + i);
            return i;

        }, executor).handle((res, thr) -> {
            if (res != null) {
                return res * 2;
            }
            if (thr != null) {
                return 0;
            }
            return 0;
        });*/
        /**
         * 方法完成后的感知
         *
         */
        /*CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("方法1 完成");
            return 1;
        }, executor).whenComplete((res, ex) -> {
            //虽然能感知异常，无法修改返回值
            System.out.println(res + ex.getMessage());
        }).exceptionally(throwable -> {
            //可以感知异常，同时返回默认值
            return 10;
        });

        */

        /**
         * 线程串行化
         * 1) thenRun 不能获取上一步的执行结果
         * thenRunAsync(() -> {
         *             System.out.println("任务2 启动了");
         *         }, executor)
         * 2）能接受上一步结果，但是无返回值
         * .thenAcceptAsync(res -> {
         *             System.out.println("任务2 启动了" + res);
         *         }, executor)
         * 3)thenApplyAsync 能接受上一步结果，有返回值
         */
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("任务1 启动，运行结果" + i);
            return i;
        }, executor).thenApplyAsync(res -> {
            System.out.println("任务2 启动，" + res);
            return res * 2;
        }, executor);

        future.get();
        System.out.println("main …… end ");


        executor.shutdown();

    }
}
